import { login, phoneLogin, loginOut, wxLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { showNotice } from '@/utils/toolclass'
import { resetRouter } from '@/router'
import router from '@/router'
import md5 from 'js-md5'
import storage from '@/utils/storage'
import Vue from 'vue'
import Vuex from 'vuex'//

Vue.use(Vuex)

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    phoneNumber: '',
    account: '',
    imageCode: '',
    codeKey: '',
    password: '',
    code: '',
    avatar: '',
    data: {},
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_DATA: (state, data) => {
    state.data = data
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PHONE_NUMBER: (state, phoneNumber) => {
    state.phoneNumber = phoneNumber
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_IMAGE_CODE: (state, imageCode) => {
    state.imageCode = imageCode
  },
  SET_CODE_KEY: (state, codeKey) => {
    state.codeKey = codeKey
  },
  SET_PASSWORD: (state, password) => {
    state.password = password
  },
  SET_CODE: (state, code) => {
    state.name = code
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_RES: (state, res) => {
    state.res = res
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // console.log(userInfo)
    const { account, imageCode, codeKey, password } = userInfo
    var newpass = password + '{' + account + '}'
    const md5Password = md5(newpass)
    // console.log(md5Password)
    return new Promise((resolve, reject) => {
      login({ account: account, code: imageCode, codeKey: codeKey, password: md5Password }).then(res => {
        // console.log(res.data)
        if (res.code === '000000') {
          const UserInfo = {
            userId: res.data.id,
            mobile: res.data.mobile,
            name: res.data.name,
            orgList: res.data.orgList,
            // companyId: res.data.companyId,
            // companyName: res.data.companyName,
            // roles: res.data.roleList,
            // currentOrgId: res.data.roleList[0].orgId,
            // crrentRoleId: res.data.roleList[0].id,
            // isAdmin: res.data.roleList[0].isAdmin,

            systemList: res.data.sysList
          }
          storage.set('data', res)
          storage.set('userInfo', UserInfo)
        } else {
          // console.log(res)
          // if (res.code === '999999') {
          //   showNotice('error', '提示', '登陆失败')
          // }
          if (res.code === '100035') {
            showNotice('error', '提示', res.msg)
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
        const { data } = res
        // storage.set('token', data.token)
        // const DataAll = data
        const ResAll = res
        // commit('SET_DATA', DataAll)
        commit('SET_RES', ResAll)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  wxLogin({ commit }, userInfo) {
    const { openid } = userInfo
    // console.log('userInfo===', userInfo)
    // console.log('openid===', openid)
    return new Promise((resolve, reject) => {
      wxLogin({ wxId: openid }).then(res => {
        // console.log('wxLogin===', res)
        if (res.code === '000000') {
          // console.log('000000', '跳转前')
          router.replace({ path: '/platform' })
          // console.log('111111', '跳转后')
          const UserInfo = {
            userId: res.data.id,
            mobile: res.data.mobile,
            name: res.data.name,
            orgList: res.data.orgList,
            systemList: res.data.sysList
          }
          storage.set('data', res)
          storage.set('userInfo', UserInfo)
        }
        if (res.code === '100034') {
          router.push({ path: '/wxreg' })
          // console.log('跳转成功===', router)
          // console.log('跳转成功22===', router.push)
          // console.log('跳转成功33===', router.push())
          // console.log('跳转成功')
          // showNotice('error', '提示', res.msg)
        }
        // if (res.code === '999999') {
        //   showNotice('error', '提示', '登陆失败')
        // }
        if (res.code === '100035') {
          showNotice('error', '提示', res.msg)
        }

        const { data } = res
        // storage.set('token', data.token)
        // const DataAll = data
        const ResAll = res
        // commit('SET_DATA', DataAll)
        commit('SET_RES', ResAll)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  phoneLogin({ commit }, userInfo) {
    const { phoneNumber, code } = userInfo
    return new Promise((resolve, reject) => {
      phoneLogin({ phoneNumber: phoneNumber, code: code }).then(res => {
        // console.log(res)
        if (res.code === '000000') {
          const UserInfo = {
            userId: res.data.id,
            mobile: res.data.mobile,
            name: res.data.name,
            orgList: res.data.orgList,
            // companyId: res.data.companyId,
            // companyName: res.data.companyName,
            // roles: res.data.roleList,
            // currentOrgId: res.data.roleList[0].orgId,
            // crrentRoleId: res.data.roleList[0].id,
            // isAdmin: res.data.roleList[0].isAdmin,

            systemList: res.data.sysList
          }
          storage.set('data', res)
          storage.set('userInfo', UserInfo)
        } else {
          // console.log(res)
          // if (res.code === '999999') {
          //   showNotice('error', '提示', '登陆失败')
          //   return
          // }
          if (res.code === '100035') {
            showNotice('error', '提示', res.msg)
            return
          } else {
            showNotice('error', '提示', res.msg)
            return
          }
        }

        const { data } = res
        // storage.set('token', data.token)
        // const DataAll = data
        const ResAll = res
        // commit('SET_DATA', DataAll)
        commit('SET_RES', ResAll)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user loginOut
  loginOut({ commit, state }, userId) {
    // console.log(userId)
    return new Promise((resolve, reject) => {
      loginOut({ userId: userId }).then((res) => {
        // console.log(res)
        if (res.code === '000000') {
          router.replace({ path: '/' })
          showNotice('success', '提示', '您已退出登陆')
          // location.reload()
          removeToken() // must remove  token  first
          resetRouter()
          storage.clear()
          commit('RESET_STATE')
          resolve(res)
        }
      }).catch(() => {
        reject()
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

